
local out = function (...) print(...) end

local fgbu_proto = Proto("spn.fgbu", "FG Basic Unit")

local fgbu_fields = {
    overhead  = ProtoField.string("fgbu.overhead", "Overhead"),
    oh_res1   = ProtoField.uint8("fgbu.overhead.res1", "RES(2bits)"),
    payload   = ProtoField.string("fgbu.payload", "Payload"),
}

fgbu_proto.fields = fgbu_fields

out("fgbu_proto registered")

function fgbu_proto.init()
    out("fgbu_proto init called")
end

local dissectfgbu

function fgbu_proto.dissector(tvbuf, pktinfo, tree)
    out("fgbu_proto.dissector called")
    -- local list = Dissector.list()
    -- for _, name in ipairs(list) do
    --     out("dissector:", name)
    -- end
    local pktlen = tvbuf:len()

    out("pktlen:", pktlen)
    if (pktlen ~= 1024) then
        local eth = Dissector.get("eth_maybefcs")
        -- local eth = Dissector.get("tcp")
        return eth:call(tvbuf, pktinfo, tree)
    end

    dissectfgbu(tvbuf, pktinfo, tree)

    return
end

dissectfgbu = function(tvbuf, pktinfo, tree)
    out("dissectfgbu called")

    pktinfo.cols.protocol:set("FGBU")
    pktinfo.cols.info = "[INC BANDWIDTH] S=1 C=0 CR=0 CA=0"
    local fgbutree = tree:add(fgbu_proto, tvbuf(0, 20))
    local fgohtree = fgbutree:add(fgbu_fields.overhead, tvbuf(0, 8))
    fgohtree:add(fgbu_fields.oh_res1, tvbuf(0, 1))

    local fgpltree = fgbutree:add(fgbu_fields.payload, tvbuf(8, 12))
    -- local tvb_version = tvbuf(0, 1)
    -- local val_version = tvb_version:bitfield(0, 6)
    -- fgbutree:add(fgbu_fields.version, tvb_version, val_version)

    -- local list = DissectorTable.heuristic_list()
    -- out("=======heuristic_list======")
    -- for _, name in ipairs(list) do
    --     out(name)
    -- end
    -- out("===========================")
end

DissectorTable.get("wtap_encap"):add(wtap.ETHERNET, fgbu_proto)
-- DissectorTable.get("wtap_encap"):add_for_decode_as(fgbu_proto)
